package com.labot.dto.mapper;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.springframework.dao.DataIntegrityViolationException;

import com.labot.dto.I18nDto;
import com.labot.model.I18n;


public class I18nMapper {
	
	public static I18nDto mapModelToDto(I18n source) {
		//Copiar las propiedades por Reflection
		I18nDto target = new I18nDto();
		try {
			BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0);
			BeanUtils.copyProperties(target, source);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return target;
    }
	
	public static List<I18nDto> mapModelListToDtoList(List<I18n> source) {
		List<I18nDto> target = new ArrayList<I18nDto>();
		for (I18n i18n : source) {
			target.add(mapModelToDto(i18n));
		}
		return target;
	}
	
	public static I18n mapDtoToModel(I18nDto source, I18n target) throws DataIntegrityViolationException {
		//Verificar el id de Hibernate...
		boolean isNew = false;
		if (source.getId() == null) {
			isNew = true;
		}
		//Copiar las propiedades por Reflection
		try {
			BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0);
			BeanUtils.copyProperties(target, source);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		
		if (isNew) {
			target.setId(null);
		}
		
        return target;
    }
	
}
